package com.suben.goodsservice.controller;


import com.suben.common.bean.R;
import com.suben.goodsservice.entity.GoodsRating;
import com.suben.goodsservice.service.GoodsRatingService;
import com.suben.goodsservice.service.RedisService;
import com.suben.goodsservice.utils.CustomStatus;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Suben
 * @since 2021-05-09
 */
@Api(tags = {"评分接口"})
@RestController
@RequestMapping("/goodsservice/goods-rating")
@CrossOrigin
@Slf4j
public class GoodsRatingController {

    @Autowired
    private GoodsRatingService goodsRatingService;

    @Autowired
    private RedisService redisService;

    // 评分接口
    @PostMapping("add")
    public R addRating(@RequestBody GoodsRating goodsRating){
        boolean save = goodsRatingService.saveOrUpdate(goodsRating);
        if (save){
            //埋点：记录用用户打分行为
            log.info(CustomStatus.PRODUCT_RATING_PREFIX + ":" + goodsRating.getUserId() +"|"+ goodsRating.getProductId() +"|"+ goodsRating.getScore() +"|"+ System.currentTimeMillis()/1000);
            // 更新redis中的数据
            updateRedis(goodsRating);
            return R.ok().message("打分成功~");
        }
        return R.error().message("打分失败~");
    }

    /**
     * 更新redis的数据库表
     * @param rating
     */
    private void updateRedis(GoodsRating rating) {
        if (redisService.exists("userId:" + rating.getUserId()) && redisService.llen("userId:" + rating.getUserId()) >= CustomStatus.REDIS_PRODUCT_RATING_QUEUE_SIZE) {
            redisService.rpop("userId:" + rating.getUserId());
        }
        String key = "userId:" + rating.getUserId();
        String value = rating.getProductId() + ":" + rating.getScore();
        redisService.leftPush(key.trim(),value.trim());
    }

}

